﻿#include <iostream>
#include <vector>
#include <queue>
using namespace std;

class Solution
{
    int m, n;
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
    bool vis[310][310];

public:
    // 733. 图像渲染
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color)
    {
        int prev = image[sr][sc];
        if (image[sr][sc] == color)
            return image;
        int m = image.size(), n = image[0].size();

        queue<pair<int, int>> q;
        q.push({ sr, sc });

        while (q.size())
        {
            pair<int, int> p = q.front();
            q.pop();
            int a = p.first, b = p.second;
            image[a][b] = color;

            for (int i = 0; i < 4; i++)
            {
                int x = a + dx[i], y = b + dy[i];
                if (x >= 0 && x < m && y >= 0 && y < n && image[x][y] == prev)
                {
                    q.push({ x,y });
                }
            }
        }
        return image;
    }

    // 200. 岛屿数量
    int numIslands(vector<vector<char>>& grid)
    {
        int ret = 0;
        m = grid.size(), n = grid[0].size();
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (grid[i][j] == '1' && !vis[i][j])
                {
                    ret++;
                    bfs(grid, i, j);
                }
            }
        }
        return ret;
    }

    void bfs(vector<vector<char>>& grid, int i, int j)
    {
        queue<pair<int, int>> q;
        q.push({ i, j });
        vis[i][j] = true;

        while (q.size())
        {
            pair<int, int> p = q.front();
            q.pop();
            int a = p.first, b = p.second;

            for (int k = 0; k < 4; k++)
            {
                int x = a + dx[k], y = b + dy[k];
                if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1' && !vis[x][y])
                {
                    vis[x][y] = true;
                    q.push({ x,y });
                }
            }
        }
    }
};

int main()
{
    /*vector<vector<int>> v{ {1,1,1} ,{1,1,0},{1,0,1} };
    Solution().floodFill(v, 1, 1, 2);
    for (int i = 0; i < v.size(); i++)
    {
        for (int j = 0; j < v[0].size(); j++)
            cout << v[i][j] << " ";
        cout << endl;
    }*/

    vector<vector<char>> v{ {'1','1','1','1','0'}, {'1','1','0','1','0'},
        {'1','1','0','0','0'},{'0','0','0','0','0'} };
    cout << Solution().numIslands(v) << endl;

    return 0;
}